<template>
  <div>
    <el-menu
        :default-active="activeIndex"
        background-color="#f7f9fa"
        class="menu"
        collapse
        mode="vertical"
        text-color="#000"
        @select="handleSelect">

      <el-tooltip v-if="!isLogin" :effect="tipTheme" content="登录" placement="left">
        <el-menu-item index="join">
          <i class="el-icon-user"></i>
        </el-menu-item>
      </el-tooltip>

      <el-submenu v-if="isLogin" index="user" popper-class="mySubmenus">
        <template slot="title">
          <el-badge :is-dot="hasUnsolvedMsg">
            <i class="el-icon-user"></i>
          </el-badge>
        </template>

        <el-submenu index="edit" popper-class="mySubmenus">
          <template slot="title">
            <i class="iconfont icon-edit"></i>
          </template>

          <el-menu-item index="avatar">
            <i class="el-icon-picture"></i>
            更换头像
          </el-menu-item>

          <el-menu-item index="name">
            <i class="el-icon-postcard"></i>
            修改用户名
          </el-menu-item>

          <el-menu-item index="password">
            <i class="el-icon-key"></i>
            修改密码
          </el-menu-item>

          <el-menu-item index="logoff">
            <i class="el-icon-switch-button"></i>
            注销账号
          </el-menu-item>
        </el-submenu>

        <el-tooltip :effect="tipTheme" content="好友" placement="left">
            <el-menu-item index="friends">
              <el-badge :is-dot="hasUnsolvedMsg">
                <i class="iconfont icon-friends"></i>
              </el-badge>
            </el-menu-item>
        </el-tooltip>

        <el-tooltip :effect="tipTheme" content="登出" placement="left">
          <el-menu-item index="logout">
            <i class="iconfont icon-logout"></i>
          </el-menu-item>
        </el-tooltip>

      </el-submenu>

      <el-tooltip :effect="tipTheme" content="设置" placement="left">
        <el-menu-item index="settings">
          <i class="el-icon-setting"></i>
        </el-menu-item>
      </el-tooltip>

      <el-tooltip :effect="tipTheme" content="上传图片" placement="left">
        <el-menu-item index="upload">
          <i class="el-icon-upload"></i>
        </el-menu-item>
      </el-tooltip>

    </el-menu>

    <el-dialog :close-on-click-modal="false" :visible.sync="isUploadDialogVis"
               center destroy-on-close title="上传图片" width="40%">
      <Upload/>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="isAvatarDialogVis"
               center title="更换头像" width="30%">
      <SetAvatar/>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="isPassDialogVis"
               center destroy-on-close title="修改密码" width="25%">
      <ChangePassword @closeChangePassDialog="closePassDialog"/>
    </el-dialog>

    <el-drawer :show-close="false" :visible.sync="isFriendListVis" size="20%">
      <img slot="title" :src="username+'.png'" alt="" loading="lazy" width="75">
      <span slot="title">{{username}}</span>
      <FriendList/>
    </el-drawer>

    <el-dialog :before-close="readyToClose" :close-on-click-modal="false"
               :visible.sync="isSettingsDialogVis" center destroy-on-close title="偏好设置"
               width="40%">
      <SettingsCard @changeSavedStatus="changeSettingsSavedStatus"/>
    </el-dialog>
  </div>
</template>

<script>
import "../icons/iconfont.css"
import {mapState, mapGetters} from "vuex";
import Upload from "@/components/Upload";
import ChangePassword from "@/components/ChangePassword";
import SettingsCard from "@/components/SettingsCard";
import FriendList from "@/components/FriendList";
import SetAvatar from "@/components/SetAvatar";

export default {
  name: "UserMenu",
  components: {
    Upload,
    ChangePassword,
    SettingsCard,
    FriendList,
    SetAvatar,
  },
  data() {
    return {
      activeIndex: '',
      isUploadDialogVis: false,
      isPassDialogVis: false,
      isAvatarDialogVis: false,
      isSettingsDialogVis: false,
      isSettingsSaved: true,
      isFriendListVis: false,
    }
  },
  computed: {
    ...mapState(['username', 'serverUrl']),
    ...mapGetters(['isLogin', 'tipTheme', 'hasUnsolvedMsg'])
  },
  methods: {
    handleSelect(key) {
      switch (key) {
        case 'upload':
          this.isUploadDialogVis = true;
          break;

        case 'join':
          this.$store.state.isFormDialogVis = true;
          break;

        case 'logout': {
          this.$confirm('确认退出登录吗？', '提示', {
            type: "warning", roundButton: true,
          }).then(() => {
            this.$store.state.username = '';
            localStorage.removeItem('token');
            this.$store.commit('updateToken');
            this.$message.success('已退出登录');
          })
          break;
        }

        case 'name': {
          this.$prompt('请输入新的用户名', '修改用户名', {
            inputValidator: (input) => {
              input = input.trim();
              const reg = /^[\w\u4e00-\u9fa5]{6,12}$/;
              if (!reg.test(input)) return '请输入仅包含中文、数字、英文字母的6-12位用户名'
              if (input === this.username) return '用户名和原来相同'
              return true
            },
            closeOnClickModal: false,
            beforeClose: async (action, instance, done) => {
              if (action === 'confirm') {
                const val = instance.inputValue.trim();
                try {
                  const res = await this.$axios.put(this.serverUrl + '/user/rename',
                      {oldName: this.username, newName: val}, {
                        headers: {Authorization: localStorage.getItem('token')}
                      })
                  if (res.data.status !== 0) {
                    this.$message.error(res.data.msg);
                  } else {
                    this.$store.state.username = val;
                    localStorage.setItem('token', res.data.msg);
                    this.$store.commit('updateToken');
                    this.$message.success('用户名修改成功');
                    done();
                  }
                } catch (err) {
                  this.$message.error(err.message);
                }
              } else {
                this.$message.info('用户名修改取消');
                done();
              }
            }
          });
          break;
        }

        case 'avatar':
          this.isAvatarDialogVis = true;
          break;

        case 'password':
          this.isPassDialogVis = true;
          break;

        case 'logoff': {
          this.$confirm('确定要注销账号吗？注销后将无法找回哦', '注销账号', {
            type: "warning"
          }).then(() => {
            this.$axios.delete(this.serverUrl + '/user/logoff', {
              headers: {Authorization: localStorage.getItem('token')}
            }).then(res => {
              if (res.data.status !== 0) {
                this.$message.error(res.data.msg);
              } else {
                this.$store.state.username = '';
                localStorage.removeItem('token');
                this.$store.commit('updateToken');
                this.$message.success('账号已注销');
              }
            }).catch(err => {
              this.$message.error(err.message);
            })
          }).catch(() => {
            this.$message.info('注销账号已取消');
          })
          break;
        }

        case 'settings':
          this.isSettingsDialogVis = true;
          break;

        case 'friends':
          this.isFriendListVis = true;
          break;
      }
    },
    closePassDialog() {
      this.isPassDialogVis = false;
    },
    readyToClose(done) {
      if (this.isSettingsSaved) return done();
      this.$confirm('设置修改尚未保存，确认离开吗？','提示', {
        type: "warning"
      }).then(()=>done())
    },
    changeSettingsSavedStatus(action) {
      this.isSettingsSaved = action;
    }
  },
}
</script>

<style lang="scss" scoped>
  .menu {
    position: fixed;
    right: 0;
    top: 30%;
  }
  i {
    font-size: 25px !important;
    color: darkgray;
    &:hover {
      color: white;
      font-size: 26px !important;
    }
  }

  span {
    font-size: 50px;
    font-family: 华文彩云;
    color: black;
  }

  .el-drawer {
    img {
      flex: 1;
      border-radius: 50%;
    }
    span {
      flex: 3;
      text-align: center;
    }
  }
</style>

<style lang="scss">
  .mySubmenus {
    .el-menu--popup {
      min-width: 50px;
    }
    .el-menu-item {
      min-width: 50px;
    }
  }
  .el-badge__content {
    top: 10px !important;
  }
</style>